import jwt from 'jsonwebtoken'
import { Article,User } from '@/common/api/model';
export default async function handler(req, res) {
    const token = req.cookies['token'];
    const query = req.body;
    if(!token){
        res.status(200);
        res.json({
            code:-1,
            data:{},
            msg: "登录已过期"
        })
        return;
    }
    const payload = jwt.verify(token, process.env.JWT_SECRET)
    if(payload.account){
        //查询用户信息 把昵称也保存进去
        User.findOne({account:payload.account}).then(user=>{
            //处理文章保存
            const newwenzhang = new Article({
                account:payload.account,
                title:query.title,
                content:query.content,
                likenum:0,
                create_time:Date.now(),
                nickname:user.nickname
            })
            newwenzhang.save().then(savewenzhang=>{
                res.status(200);
                res.json({
                    code:1,
                    data:{
                        
                    },
                    msg: "发布成功"
                })
            }).catch(err=>{
                res.status(200).json({
                    code:-1,
                    data:{
                        
                    },
                    msg: "发布失败"
                })
            })
        })
        
        return;
    }else{
        res.status(200);
        res.json({
            code:-1,
            data:{},
            msg: "登录已过期，请重新登录"
        })
        return;
    }
}